package com.zyl.blog.tasks.utils;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;


/**
 * 异步执行工具类
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.tasks.utils
 * @ClassName: AsyncUtil
 * @Author FinalFantasy
 * @Date 2025/8/13-08:33
 */
@Component
public class AsyncUtil {

    /**
     * 异步执行任务（使用JDK24虚拟线程）
     */
    @Async
    public CompletableFuture<Void> execute(Runnable runnable) {
        return CompletableFuture.runAsync(runnable, (Executor) Thread.ofVirtual().factory());
    }

    /**
     * 异步执行有返回值的任务
     */
    @Async
    public <T> CompletableFuture<? extends T> execute(Callable<T> callable) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                return callable.call();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
}